#include <bits/stdc++.h>

using namespace std;
class Solution
{
public:
    int minimumValueSum(vector<int> &nums, vector<int> &andValues)
    {
        this->n = nums.size();
        this->m = andValues.size();
        memo.resize(n * m);
        int res = dfs(0, 0, INF, nums, andValues);
        return res == INF ? -1 : res;
    }

private:
    static const int INF = (1 << 20) - 1;
    vector<unordered_map<int, int>> memo;
    int n, m;
    int dfs(int i, int j, int cur, vector<int> &nums, vector<int> &andValues)
    {
        if (i == n && j == m)
        {
            return 0;
        }
        if (i == n || j == m)
        {
            return INF;
        }
        int key = i * m + j;
        if (memo[key].count(cur))
        {
            return memo[key][cur];
        }
        cur &= nums[i];
        if (cur & andValues[j] < andValues[j])
        {
            return INF;
        }

        int res = dfs(i + 1, j, cur, nums, andValues);
        if (cur == andValues[j])
        {
            res = min(res, nums[i] + dfs(i + 1, j + 1, cur, nums, andValues));
        }
        return memo[key][cur] = res;
    }
};
int main()
{
    vector<int> nums;
    int num;
    while (cin >> num)
    {
        nums.push_back(num);
    }

    vector<int> andValues;
    while (cin >> num)
    {
        andValues.push_back(num);
    }

    Solution obj;
    int result = obj.minimumValueSum(nums, andValues);

    cout << "Minimum value sum: " << result << endl;
    // system("pause");
    return 0;
}